package com.yanqu.road.server.gameplayer.module.exchange;

import com.yanqu.road.logic.bussiness.servercenter.ExchangeBussiness;
import com.yanqu.road.entity.player.UserExchange;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.timer.activity.ActivityReloadTask;

import java.util.Map;

public class ExchangeModule extends GeneralModule {

    private Map<String, UserExchange> userExchangeMap;

    public ExchangeModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
//        修改为lazyLoad ActivityReloadTask 定时器检测空 空则初始化
//        userExchangeMap = ExchangeBussiness.getUserExchangeMap(player.getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        if (userExchangeMap == null) {
            return true;
        }
        for(UserExchange userExchange : userExchangeMap.values()){
            if(userExchange.isInsertOption()){
                ExchangeBussiness.addUserExchange(userExchange);
            }else if(userExchange.isUpdateOption()){
                ExchangeBussiness.updateUserExchange(userExchange);
            }
        }
        return true;
    }

    /**
     * 是否已加载兑换码模块
     * @return
     */
    public boolean isLoad() {
        if (userExchangeMap == null) {
            return false;
        }
        return true;
    }

    /**
     * 定时器扫描加载
     * @return
     */
    public boolean lazyLoad() {
        if (userExchangeMap == null) {
            userExchangeMap = ExchangeBussiness.getUserExchangeMap(player.getUserId());
            log.debug("lazy load exchange code : " + player.getUserId());
        }
        return true;
    }

    public boolean isUseExchangeKey(String exchangeKey) {
        synchronized (userExchangeMap) {
            return userExchangeMap.containsKey(exchangeKey);
        }
    }

    public void addUserExchange(String exchangeKey) {
        UserExchange userExchange = new UserExchange();
        userExchange.setUserId(player.getUserId());
        userExchange.setExchangeKey(exchangeKey);
        userExchange.setUseTime(System.currentTimeMillis() / 1000);
        userExchange.setInsertOption();
        synchronized (userExchangeMap) {
            if(!userExchangeMap.containsKey(exchangeKey)){
                userExchangeMap.put(userExchange.getExchangeKey(), userExchange);
            }
        }
    }
}
